<template>
  <div>
    <DialogNew
      v-model="is_show"
      @close="close"
      title="品牌商品设置"
      width="500px"
    >
      <div v-loading="loading">
        <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" style="margin-left: 10%">
          <el-form-item v-if="fasle" prop="id" />
          <el-form-item v-if="fasle" prop="brand_id" />
          <el-form-item
            v-if="action === 'returnPointRatio'"
            label="返点比例"
            prop="return_point_ratio"
          >
            <el-input-number
              class="input"
              v-model="form.return_point_ratio"
              :min="0"
              placeholder="请输入返点比例"
              :controls="false"
              @wheel.native.prevent="stopScroll($event)"
            />
          </el-form-item>
        </el-form>

        <div class="discount-setting" v-if="action === 'setDiscount'">
          <div class="dis-label">设置规格组：</div>
          <div class="discount_box">
            <template v-for="(item, index) in SkuDiscount" :key="index">
              <div class="discount-item">
                <div class="discount-row">
                  <el-input
                    v-model="item.discount"
                    placeholder="请输入规格组名称"
                    style="width: 200px"
                    :disabled="action === 'view'"
                  />
                  <div class="discount-buttons">
                    <el-button type="primary" plain @click="handleAddDiscount">
                      添加
                    </el-button>
                    <el-button
                      v-if="SkuDiscount.length > 1"
                      type="danger"
                      plain
                      @click="handleRemoveDiscount(index)"
                    >
                      删除
                    </el-button>
                    <el-button
                      type="info"
                      plain
                      @click="selectOtherDiscount(index)"
                    >
                      选择剩余规格
                    </el-button>
                  </div>
                </div>
                <div class="discount-row" style="margin-top: 10px">
                  <el-select
                    v-model="item.goods_spec_value_ids"
                    style="width: 100%"
                    :disabled="action === 'view'"
                    multiple
                    placeholder="请选择规格组合"
                    clearable
                  >
                    <el-option
                      v-for="sku in skuList"
                      :key="sku.goods_spec_value_ids"
                      :label="sku.goods_spec_value_names"
                      :value="sku.goods_spec_value_ids"
                    />
                  </el-select>
                </div>
              </div>
            </template>
          </div>
        </div>
      </div>

      <div class="discount-setting" v-if="action === 'setGeneralDiscount'">
        <div class="discount-list">
          <div
            v-for="item in discountList"
            :key="item.id"
            class="discount-item"
          >
            <div class="discount-header">
              <h3 class="goods-name">{{ item.goods_name }}</h3>
              <div class="spec-info">规格：{{ item.discount }}</div>
            </div>
            <div class="discount-content">
              <div
                v-for="(dis, disIndex) in item.goods_sku_discount"
                :key="disIndex"
                class="discount-row"
              >
                <span class="discount-label">折扣{{ disIndex + 1 }}：</span>
                <el-input-number
                  v-model="dis.discount"
                  :min="0"
                  :max="10"
                  :precision="2"
                  :step="0.1"
                  :controls="false"
                  class="discount-input"
                  placeholder="请输入折扣"
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="is_show = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" v-repeat>
          确定
        </el-button>
      </template>
    </DialogNew>
  </div>
</template>

<script setup>
  import DialogNew from '@/components/DialogNew/index.vue'
  import { stopScroll } from '@/utils/helper'
  import {
    setReturnPointRatio,
    getFromAdminDiscount,
    setDiscount,
    getFromAdminGeneralDiscount,
    setGeneralDiscount,
  } from '@/api/goods'
  import { message } from '@/utils/helper'
  const is_show = ref(false)

  const loading = ref(false)
  const action = ref('add')
  const form = reactive({
    id: undefined,
    brand_id: undefined,
    return_point_ratio: undefined,
  })
  const open = async (type, row) => {
    action.value = type
    if (row) {
      const { id, brand_id, return_point_ratio } = row
      Object.assign(form, {
        id,
        brand_id,
        return_point_ratio,
      })
    }
    // 根据类型获取对应的列
    switch (type) {
      case 'return_point_ratio':
        rules.value = {
          return_point_ratio: {
            required: true,
            message: '请填写返点比例',
            trigger: 'change',
          },
        }
        break
      case 'setDiscount':
        getSkuGoods()
        break
      case 'setGeneralDiscount':
        // 获取通用折扣列表
        getSetDiscountList()
        break
    }
    is_show.value = true
  }

  const close = () => {
    skuList.value = []
    SkuDiscount.value = [
      {
        discount: '',
        goods_spec_value_ids: [],
        goods_discount_id: 0,
      },
    ]
    formRef.value.resetFields()
  }

  const rules = ref({})

  const emits = defineEmits(['fetch-data'])

  const formRef = ref(null)
  const handleSubmit = () => {
    formRef.value.validate(async (valid) => {
      if (valid) {
        switch (action.value) {
          case 'returnPointRatio':
            await setReturnPointRatio({
              id: form.id,
              brand_id: form.brand_id,
              return_point_ratio: form.return_point_ratio,
            })
            break
          case 'setDiscount':
            if (
              SkuDiscount.value.some(
                (i) => i.discount === '' || i.goods_spec_value_ids.length === 0
              )
            )
              return message('存在为空的折扣信息', 'error')
            await setDiscount({
              id: form.id,
              brand_id: form.brand_id,
              set_discount: JSON.stringify(
                SkuDiscount.value.map((i) => ({ ...i, goods_id: form.id }))
              ),
            })
            break
          case 'setGeneralDiscount':
            const arr = discountList.value
              .map((i) => i.goods_sku_discount)
              .flat()
              .filter((c) => c.discount != 0)
            await setGeneralDiscount({
              id: form.id,
              brand_id: form.brand_id,
              goods_sku_discount: arr,
            })
            break
        }
        emits('fetch-data')
        message('设置成功')
        is_show.value = false
      }
    })
  }

  // 获取sku商品数据
  const getSkuGoods = async () => {
    const { data } = await getFromAdminDiscount({
      id: form.id,
      brand_id: form.brand_id,
    })
    skuList.value = data.goods_sku_data
    data.set_discount.length !== 0 && (SkuDiscount.value = data.set_discount)
  }
  const skuList = ref([])
  const SkuDiscount = ref([
    {
      discount: '',
      goods_spec_value_ids: [],
      goods_discount_id: 0,
    },
  ])

  const handleAddDiscount = () => {
    SkuDiscount.value.push({
      discount: '',
      goods_spec_value_ids: [],
      goods_discount_id: 0,
    })
  }
  const handleRemoveDiscount = (discountIndex) => {
    SkuDiscount.value.splice(discountIndex, 1)
  }
  const selectOtherDiscount = (index) => {
    const allSelectSkuDiscount_values = [
      ...new Set(
        SkuDiscount.value.map((ids) => ids.goods_spec_value_ids).flat()
      ),
    ]
    const other = skuList.value
      .filter(
        (ic) => !allSelectSkuDiscount_values.includes(ic.goods_spec_value_ids)
      )
      .map((ic) => ic.goods_spec_value_ids)
    if (other.length == 0) return message('已经全部选中了', 'warning')
    SkuDiscount.value[index].goods_spec_value_ids = [
      ...SkuDiscount.value[index].goods_spec_value_ids,
      ...other,
    ]
  }
  const discountList = ref([])
  const getSetDiscountList = async () => {
    const res = await getFromAdminGeneralDiscount({
      id: form.id,
      brand_id: form.brand_id,
    })
    discountList.value = res.data
  }
  defineExpose({ open })
</script>

<style lang="scss" scoped>
  ::deep(.el-dialog__header) {
    padding-bottom: 0 !important;
  }
  .input {
    width: 285px;
  }

  .discount_box {
    display: flex;
    flex-direction: column;
    gap: 20px;
    padding: 0 20px;
    flex: 1;

    .discount-item {
      padding: 15px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      background-color: #f8f9fa;

      .discount-row {
        display: flex;
        align-items: center;
        gap: 10px;

        .discount-buttons {
          margin-left: 10px;
          display: flex;
          gap: 10px;
        }
      }
    }
  }

  .discount-setting {
    padding: 0 20px;

    .discount-list {
      display: flex;
      flex-direction: column;
      gap: 20px;
    }
    .dis-label {
      font-size: 14px;
      color: #606266;
      margin: 10px 20px;
    }

    .discount-item {
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
      overflow: hidden;

      .discount-header {
        padding: 16px 20px;
        background: #f5f7fa;
        border-bottom: 1px solid #ebeef5;

        .goods-name {
          margin: 0 0 8px 0;
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }

        .spec-info {
          font-size: 14px;
          color: #606266;
        }
      }

      .discount-content {
        padding: 16px 20px;
        display: flex;
        flex-wrap: wrap;
        gap: 20px;
        .discount-row {
          display: flex;
          align-items: center;
          margin-bottom: 12px;

          &:last-child {
            margin-bottom: 0;
          }

          .discount-label {
            width: 55px;
            font-size: 14px;
            color: #606266;
          }

          .discount-input {
            width: 120px;
          }

          .discount-unit {
            margin-left: 8px;
            color: #909399;
          }
        }
      }
    }
  }
</style>
